package club.ruanx.movie.controller;

import club.ruanx.bean.PageBean;
import club.ruanx.bean.ResultVO;
import club.ruanx.movie.entity.Movie;
import club.ruanx.movie.service.MovieService;
import club.ruanx.movie.util.SolrUpdater;
import club.ruanx.search.feign.client.SolrMovieServiceClient;
import club.ruanx.spider.repository.DoubanMovieRepository;
import club.ruanx.util.CollectionUtils;
import club.ruanx.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author 阮胜
 * @date 2018/12/22 14:40
 */
@RestController
@RequestMapping("/dev")
public class DeveloperController {

    private final MovieService movieService;
    private final DoubanMovieRepository doubanMovieRepository;
    private final SolrMovieServiceClient solrMovieServiceClient;
    private final SolrUpdater solrUpdater;

    public DeveloperController(MovieService movieService, DoubanMovieRepository doubanMovieRepository, SolrMovieServiceClient solrMovieServiceClient, SolrUpdater solrUpdater) {
        this.movieService = movieService;
        this.doubanMovieRepository = doubanMovieRepository;
        this.solrMovieServiceClient = solrMovieServiceClient;
        this.solrUpdater = solrUpdater;
    }

    /**
     * 打乱电影封面
     */
    @GetMapping("/movie/reset/cover")
    public ResultVO resetMovieCover() throws IOException {
        ClassPathResource resource = new ClassPathResource("static/url.json");
        String json = StringUtils.readFromFile(resource.getFile().getAbsolutePath());
        List<String> urlList = Objects.requireNonNull(JSON.parseArray(json, JSONObject.class))
                .stream()
                .map(jsonObject -> jsonObject.getString("url"))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(urlList)) {
            return ResultVO.builder().message("找不到初始封面地址数据").success(false).build();
        }
        List<Movie> movieList = movieService.findAll();
        for (int i = 0; i < movieList.size(); i++) {
            Movie movie = movieList.get(i);
            int index = i % urlList.size();
            movie.setCover(urlList.get(index));
            movieService.save(movie);
        }
        return ResultVO.builder().message("成功更新" + movieList.size() + "条数据").success(true).build();
    }

    /**
     * 打乱电影评分
     *
     * @param min
     * @return
     */
    @GetMapping("/movie/shuffle/rate")
    public ResultVO shuffleRate(@RequestParam int min) {
        if (min <= 0) {
            min = 1;
        } else if (min >= 10) {
            min = 9;
        }
        final int minRate = min * 10;
        Random r = new Random();
        List<Movie> movieList = movieService.findAll();
        movieList.forEach(movie -> {
            float rate = (r.nextInt(100 - minRate) + minRate) / 10f;
            movie.setRate(rate);
            movieService.save(movie);
        });
        return ResultVO.builder().success(true).message("随机设置评分成功,共设置" + movieList.size() + "条数据").build();
    }

    /**
     * 重置爬虫服务器中的Synchronization字段
     *
     * @param pageBean
     * @return
     */
    @GetMapping("/doubanMovie/reset/sync")
    public ResultVO resetSync(PageBean pageBean) {
        doubanMovieRepository.findAllBySynchronization(true, pageBean.toPageable())
                .getContent().forEach(doubanMovie -> {
            doubanMovie.setSynchronization(false);
            doubanMovieRepository.save(doubanMovie);
        });
        return ResultVO.builder().success(true).message("重置同步状态成功").build();
    }

    @GetMapping("/solr/sync")
    public ResultVO syncSolrMovies() {
        List<Movie> movies = movieService.findAll();
        int count = 0;
        for (Movie movie : movies) {
            try {
                solrUpdater.updateToSolrServer(movie);
                count++;
            } catch (Exception e) {
                //ignore
            }
        }
        return ResultVO.builder().success(true).message("同步" + count + "条数据成功").build();
    }
}
